package com.bwie.config;

//import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * TODO
 *
 * @Description
 * @Author 36167
 * @Date 2025/3/12 9:36
 **/

@Component
//@Slf4j
public class GateWaterHaloed implements GlobalFilter, Ordered {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String ip = request.getRemoteAddress().toString();
        String url = request.getURI().getPath();

        if (judge(url)){
//          log.info("白名单为:{}",url);
          return chain.filter(exchange);
        }

        String token = request.getHeaders().getFirst("token");
        if (token==null){
//            log.error("token为空:{}",url);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        String s = stringRedisTemplate.opsForValue().get(token);
        if (s==null){
//            log.error("token不存在:{}",url);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        Boolean b = stringRedisTemplate.hasKey(token);
        if (!b){
//            log.error("token失效:{}",url);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

     return chain.filter(exchange);

    }

    private boolean judge(String url) {
        ArrayList<String> list = new ArrayList<>();
        list.add("/user/login");
        if (judge1(url,list)){
            return true;
        }else {
            return false;
        }
    }

    private boolean judge1(String url, ArrayList<String> list) {
        AtomicBoolean ref= new AtomicBoolean(false);
         list.stream().filter(a->url.contains(a)).forEach(a->{
             ref.set(true);
         });

         return ref.get();
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
